<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="q.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                :label="item.cate_name"
                :value="item.id"
                v-for="item in ArtCateList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArticleList()"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="resetForm"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="pubDialogVisible = true"
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="ArticleList" style="width: 100%" border stripe>
        <el-table-column label="文章标题">
          <template v-slot="{ row }">
            <el-link type="primary" @click="showDetail(row.id)">{{
              row.title
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="文章分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="{ row }">
            {{ formatData(row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="removeDetail(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 20]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 发表文章对话框start -->
    <el-dialog
      title="发表文章"
      :visible.sync="pubDialogVisible"
      fullscreen
      :before-close="handleClose"
      @closed="closeResetForm"
    >
      <!-- 发布文章的对话框 -->
      <el-form
        :model="pubForm"
        :rules="pubFormRules"
        ref="pubFormRef"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            v-model="pubForm.cate_id"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in ArtCateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 文章内容 -->
        <el-form-item label="文章内容" prop="content">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img
            src="../../../assets/images/cover.jpg"
            alt=""
            class="cover-img"
            ref="imgRef"
          />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFile"
            @change="onChangeFile"
          />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFile.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticle('已发布')"
            >发布</el-button
          >
          <el-button type="info" @click="pubArticle('草稿')"
            >存为草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 发表文章对话框end -->

    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ formatData(artDetail.pub_date)}}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <img
        :src=" 'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img"
        alt=""
      />

      <div v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import defaultImg from '@/assets/images/cover.jpg'
export default {
  name: 'ArtList',
  data() {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      // 控制发布文章对话框的显示与隐藏
      pubDialogVisible: false,
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      // 表单的验证规则对象
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [
          { required: true, message: '请选择文章分类', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      ArtCateList: [],
      // 保存文章列表
      ArticleList: [],
      // 存储文章总条数
      total: 0,
      // 控制文章预览区的对话框的显示和隐藏
      detailVisible: false,
      // 保存文章详情页的数据
      artDetail: {}
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    // 获取文章分类的数据
    async getArtCateList() {
      // 发送请求获取数据
      const { data: res } = await this.$http.get('/my/cate/list')
      // console.log(res)
      if (res.code === 0) {
        this.ArtCateList = res.data
      }
    },
    // 获取图片
    onChangeFile(e) {
      const fileList = e.target.files
      if (fileList.length > 0) {
        // 选择了图片
        console.log(fileList[0])
        this.pubForm.cover_img = fileList[0]
        // URL.createObjectURL 能够将图片对象存储到程序的内存中，返回一个地址
        const url = URL.createObjectURL(fileList[0])
        this.$refs.imgRef.setAttribute('src', url)
      } else {
        this.pubForm.cover_img = null
        this.$refs.imgRef.setAttribute('src', defaultImg)
      }
    },
    // 发布文章
    pubArticle(state) {
      this.pubForm.state = state
      // 表单预校验
      this.$refs.pubFormRef.validate(async(valid) => {
        if (!valid) return this.$message.error('请完善文章信息！')
        // 判断是否提供了文章封面
        if (!this.pubForm.cover_img) return this.$message.error('请选择文章封面！')
        // FormData 格式：网络传输入数据的一种格式
        const fd = new FormData()
        // fd.append('title', this.pubForm.title)
        // fd.append('cate_id', this.pubForm.cate_id)
        // fd.append('content', this.pubForm.content)
        // fd.append('state', this.pubForm.state)
        // fd.append('cover_img', this.pubForm.cover_img)

        // for (const key in this.pubForm) {
        //   fd.append(key, this.pubForm[key])
        // }

        // const arr = Object.keys(this.pubForm)
        // arr.forEach((key) => {
        //   fd.append(key, this.pubForm[key])
        // })
        // 发送请求
        Object.keys(this.pubForm).forEach((key) =>
          fd.append(key, this.pubForm[key])
        )
        const { data: res } = await this.$http.post('/my/article/add', fd)
        // 提醒用户
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 关闭dialog对话框
        this.pubDialogVisible = false
        // 清空input type=file的值 防止发布文章之后不能选择同一个照片
        this.$refs.iptFile.value = ''
        // 重新获取列表的数据
        this.getArticleList()
      })
    },
    // 重置表单
    closeResetForm() {
      this.$refs.pubFormRef.resetFields()
      this.pubForm.cover_img = null
      this.$refs.imgRef.setAttribute('src', defaultImg)
      this.pubForm.state = ''
    },
    // 获取文章列表数据
    async getArticleList() {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      // 保存到data
      if (res.code === 0) {
        this.ArticleList = res.data
        this.total = res.total
      }
    },
    // 格式化时间
    formatData(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.q.pagenum = 1
      this.getArticleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.q.pagenum = val
      this.getArticleList()
    },
    // 重置表单
    resetForm() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.getArticleList()
    },
    // 显示详情页的数据
    async showDetail(id) {
      // 请求详情数据
      const { data: res } = await this.$http.get('/my/article/info', {
        params: { id }
      })
      if (res.code === 0) {
        this.artDetail = res.data
        // 展示对话框
        this.detailVisible = true
      }
    },
    // 删除文章
    removeDetail(id) {
      // 1. 询问用户是否要删除
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 发送请求
          const { data: res } = await this.$http.delete('/my/article/info', {
            params: { id }
          })
          if (res.code !== 0) return this.$message.error(res.message)
          this.$message.success(res.message)
          // 判断页面的数据是否只有一条
          if (this.ArticleList.length === 1 && this.q.pagenum > 1) {
            this.q.pagenum--
          }
          // 重新获取数据
          this.getArticleList()
        })
        .catch((err) => err)
    }
  },
  created() {
    this.getArtCateList()
    this.getArticleList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-container {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 15px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
